package com.uft.utils;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;



public class UftUtils {
	public static String TASK_RUNNING="RUNNING";
	public static String TASK_NOT_RUNNING="NOTRUNNING";
	public static String TASK_COMPLETE="COMPLETE";
	public static String TASK_NOT_EXISTS="NOTEXITS";
	public static String TASK_EXIST="EXISTS";
	public static String RESTART_GROUP_PATTERN="restart_(.*)";
	public static String RESTART_GROUP_PATTERN_PREF_NAME="RESTART_GROUP_PATTERN";
	public static String SERVER_PREF_SUFFIX="SERVER_NAME_SUFFIX";
	public static String SERVER_PREF_PREFIX="SERVER_NAME_PREFIX";
	private  static Logger  logger = Logger.getLogger(UftUtils.class);
	public static String getApplicationName(String serverName, String  suffix , String prefix){
		
		if(suffix != null && !suffix.equalsIgnoreCase("")){
			serverName=serverName.replaceAll(suffix+"$", "");
		}
		if(prefix != null && !prefix.equalsIgnoreCase("")){
			
			serverName= serverName.replaceAll("^"+prefix,"");
		}
		return serverName;
	}
	
	public static boolean matchApplicationName(String appName,List<String> groups ){
		Boolean result= false;
		if(appName != null && !appName.equalsIgnoreCase("")){
			logger.info("appName : "+appName);
			for(String ad:groups){
				logger.info("group : "+ad);
				int index1=ad.indexOf(appName);
				logger.debug("match index : "+index1);
				if (index1 != -1){
					logger.info("match index : true");
					result=true;
					break;
				}
			}
		}
		return result;
	}
	public static boolean hostExists(String hostname){
		return true;
		
	}
	public static String getResourcePath(String fileName){
		String directoryPath=System.getProperty("com.uft.config.path");
		String filePath="";
		if(directoryPath != null){
			logger.info("Found com.warf.config.path: "+directoryPath);
			filePath=directoryPath+'/'+fileName;
		}else{
			filePath=Thread.currentThread().getContextClassLoader().getResource(fileName).getPath();
		}
		
		return filePath;
	}
	public static String getBody(HttpServletRequest request) throws IOException {

	    String body = null;
	    StringBuilder stringBuilder = new StringBuilder();
	    BufferedReader bufferedReader = null;

	    try {
	        InputStream inputStream = request.getInputStream();
	        if (inputStream != null) {
	            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
	            char[] charBuffer = new char[128];
	            int bytesRead = -1;
	            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
	                stringBuilder.append(charBuffer, 0, bytesRead);
	            }
	        } else {
	            stringBuilder.append("");
	        }
	    } catch (IOException ex) {
	        throw ex;
	    } finally {
	        if (bufferedReader != null) {
	            try {
	                bufferedReader.close();
	            } catch (IOException ex) {
	                throw ex;
	            }
	        }
	    }

	    body = stringBuilder.toString();
	    return body;
	}
	
	public static String formatXMLStr(String str){
		if(str != null){
    		return str;
    	}else{
    		return "";
    	}
	}
	public static List<String> parseRestartGroups(String groupsStr, String patternStr) {
		if(patternStr == null || patternStr.equalsIgnoreCase("")){
			patternStr=RESTART_GROUP_PATTERN;
		}
		List<String> groupsList=new ArrayList<String>();
		if(groupsStr != null && !groupsStr.equalsIgnoreCase("")){
			String gStr=groupsStr.replaceAll("\"", "");
			logger.debug("parseRestartWarfGroups before: "+gStr);
			
			String[] temp;
			// TODO Auto-generated method stub
			String delimeter = ",";
			temp = gStr.split(delimeter);  
			Pattern pattern = Pattern.compile(patternStr,Pattern.CASE_INSENSITIVE);
			  
			for(int i =0; i < temp.length ; i++){
				logger.debug("group : "+temp[i]);
				Matcher matcher = pattern.matcher(temp[i]);
				if(matcher.matches()){
					groupsList.add((temp[i]));
				}
				
			}
		}
		
		logger.debug("groups List:"+groupsList.toString());
		return groupsList;
	}
	
	

	
	public static boolean isAdministrator(String groupsStr, List<String> groups){
		boolean result=false;
		if(groupsStr != null && !groupsStr.equalsIgnoreCase("")){
			String gStr=groupsStr.replaceAll("\"", "");
			logger.info("isAdministrator groups:"+gStr);
			if(gStr != null && !gStr.equalsIgnoreCase("")){
				for(String ad:groups){
					int index1=gStr.indexOf(ad);
					if (index1 != -1){
						result=true;
						break;
					}
				}
			}
		}
		return result;
	}
	
	
}
